
import React from 'react'
import ReactDOM from 'react-dom'
import * as DemoAction  from '../../actions/DemoAction';
import { connect }  from 'react-redux';

import DemoSettingTools from './DemoSettingTools'
import DemoSettingList from './DemoSettingList'
import DemoSettingEdit from './DemoSettingEdit'

class DemoSettingBody extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      activeData: {}
    }
  }

  componentDidMount() {
    var self = this;
    this.$modal = $(ReactDOM.findDOMNode(this.refs.DemoSettingEdit))
    this.props.dispatch(
      DemoAction.loadDemoDataAsync()
    )
  }

  onCreateClick() {
    this.setState({
      activeData: {}
    })
    this.$modal.modal("show")
  }

  onDataCreate(data) {
    this.props.dispatch(
      DemoAction.createDemoData(data)
    )
    this.setState({
      activeData: data
    })
    this.$modal.modal("hide");
  }

  onDataUpdate(data) {
    this.props.dispatch(
      DemoAction.editDemoData(data.id, data)
    )
    this.setState({
      activeData: data
    })
    this.$modal.modal("hide");
  }

  onEditClick(index) {
    if (index < this.props.data.length) {
      this.setState({
        activeData: this.props.data[index]
      })
      this.$modal.modal("show")
    }
  }

  onDeleteClick(index) {
    var data = this.props.data[index];
    this.props.dispatch(
      DemoAction.deleteDemoData(data.id)
    )
  }

  render() {
    var self = this;
    console.log(this.props.data)
    return (
      <div className="content-body demo-content-body" >
        <DemoSettingTools
          onCreateClick={this.onCreateClick.bind(self)}/>
        <DemoSettingList
          data = {this.props.data}
          onDeleteClick = {this.onDeleteClick.bind(self)}
          onEditClick = {this.onEditClick.bind(self)}/>
        <DemoSettingEdit
          ref = "DemoSettingEdit"
          data = {this.state.activeData}
          isEdit = {this.state.activeData.id != undefined}
          onDataUpdate = {this.onDataUpdate.bind(self)}
          onDataCreate = {this.onDataCreate.bind(self)}/>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return { data: state.demos }
}

export default connect(mapStateToProps)(DemoSettingBody);
